import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider as NavigationThemeProvider,
} from "@react-navigation/native";
import { useFonts } from "expo-font";
import { Stack, useRouter, useSegments } from "expo-router";
import * as SplashScreen from "expo-splash-screen";
import { StatusBar } from "expo-status-bar";
import { useEffect } from "react";
import "react-native-reanimated";

import { AuthProvider, useAuth } from "@/contexts/AuthContext";
import { ThemeProvider } from "@/contexts/ThemeContext";
import { UpdateManager } from '@/components/UpdateManager';

import { useColorScheme } from "@/hooks/useColorScheme";

// Prevent the splash screen from auto-hiding before asset loading is complete.
SplashScreen.preventAutoHideAsync();

// 认证路由保护组件
function AuthenticationGuard({ children }: { children: React.ReactNode }) {
  const { userToken, isLoading } = useAuth();
  const segments = useSegments();
  const router = useRouter();

  useEffect(() => {
    if (isLoading) return;

    const inAuthGroup = segments[0] === 'auth';

    if (!userToken && !inAuthGroup) {
      // 如果没有token且不在auth路由组，重定向到登录页面
      router.replace('/auth/login');
    } else if (userToken && inAuthGroup) {
      // 如果有token且在auth路由组，重定向到主页
      router.replace('/(tabs)');
    }
  }, [userToken, segments, isLoading]);

  if (isLoading) {
    // 可以在这里添加一个加载指示器
    return null;
  }

  return <>{children}</>;
}

export default function RootLayout() {
  const colorScheme = useColorScheme();
  const [loaded] = useFonts({
    SpaceMono: require("../assets/fonts/SpaceMono-Regular.ttf"),
  });

  useEffect(() => {
    if (loaded) {
      SplashScreen.hideAsync();
    }
  }, [loaded]);

  if (!loaded) {
    return null;
  }

  return (
    <AuthProvider>
      <ThemeProvider>
        <NavigationThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
          <AuthenticationGuard>
            <Stack initialRouteName='(tabs)'>
              <Stack.Screen name='(tabs)' options={{ headerShown: false }} />
              <Stack.Screen name='auth' options={{ headerShown: false }} />
              <Stack.Screen name='chat' options={{ headerShown: false }} />
              <Stack.Screen name='chat/[id]' options={{ headerShown: false }} />
              {/* <Stack.Screen name='auth/register' options={{ headerShown: false }} />
              <Stack.Screen name='auth/login' options={{ headerShown: false }} /> */}
              <Stack.Screen
                name='chat/ai-assistant'
                options={{ headerShown: false }}
              />
              <Stack.Screen name='profile' options={{ headerShown: false }} />
              <Stack.Screen name='profile/activities' options={{ headerShown: false }} />
              <Stack.Screen name='profile/favorites' options={{ headerShown: false }} />
              <Stack.Screen name='profile/health' options={{ headerShown: false }} />
              <Stack.Screen name='profile/settings' options={{ headerShown: false }} />
              <Stack.Screen name='profile/help' options={{ headerShown: false }} />
              <Stack.Screen name='profile/edit-profile' options={{ headerShown: false }} />
              <Stack.Screen name='profile/change-password' options={{ headerShown: false }} />

              <Stack.Screen name='+not-found' />
            </Stack>
            <UpdateManager />
            <StatusBar style='auto' />
          </AuthenticationGuard>
        </NavigationThemeProvider>
      </ThemeProvider>
    </AuthProvider>
  );
}
